package com.leenmvc.core.security.service.core;

import com.google.code.kaptcha.Producer;
import com.leenmvc.core.annotation.TransactionMulti;
import com.leenmvc.core.base.BaseService;
import com.leenmvc.core.security.entity.core.SysUser;
import com.leenmvc.core.security.entity.core.SysUserCaptcha;
import com.leenmvc.core.utils.DateUtils;
import com.leenmvc.core.utils.dictionary.Dict;
import com.leenmvc.core.utils.mail.BodyPartUtil;
import com.leenmvc.core.utils.mail.MailMessage;
import com.leenmvc.core.utils.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.Date;

/**
 * 用户验证码功能
 * @author zhousc
 * @date 2020/05/27
 */
@Service
public class SysUserCaptchaService extends BaseService<SysUserCaptcha> {

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService userService;

    /**
     * 发送验证码到手机或邮箱
     */
    @TransactionMulti
    public void sendCodeToDevice(String number,int type,int function){
        switch (function){
            case 1:
                if (type == 2){
                    sendEmailCodeForPwd(number);
                }else {

                }
                break;
            default:
                break;
        }
    }

    /**
     * 验证验证码是否正确
     * @param number  手机号或邮箱
     * @param type    1手机号2邮箱
     * @param code    验证码
     * @return 0 成功  1 验证码错误 2 验证码已失效
     */
    public int verifyCode(String number,int type,String code){
        Long userId = null;
        if (type == 1){

        }else if(type == 2){
            SysUser user = userService.get("email", number);
            userId = user.getId();
        }
        SysUserCaptcha sysUserCaptcha = get("userId", userId, "type", type);
        if (code.equals(sysUserCaptcha.getCode())){
            Date expireDate = sysUserCaptcha.getExpireDate();
            if (System.currentTimeMillis() < expireDate.getTime()){
                // 验证成功后，设置为过期时间
                Date date = DateUtils.addDateMinutes(expireDate, -5);
                sysUserCaptcha.setExpireDate(date);
                update(sysUserCaptcha);
                return 0;
            }
            return 2;
        }
        return 1;
    }

    /**
     * 发送功能为找回密码的邮箱验证码模板
     */
    public void sendEmailCodeForPwd(String number){
        // 生成验证码，
        String code = producer.createText();
        // 通过邮箱号获取用户id
        SysUser user = userService.get("email", number);
        Long userId = user.getId();
        // 将验证码插入数据库或者修改数据
        insertOrUpdate(userId,2,code);
        // 发送邮件
        MailMessage mailMessage = new MailMessage();
        mailMessage.setSender( Dict.get("email","username").getDictValue());
        mailMessage.setReceiver(number);
        mailMessage.setSubject("智慧环卫平台密码修改");
        try {
            mailMessage.setAllFile(MailUtil.createMailContent(BodyPartUtil.createTextPart("你好，您的验证码为："+code+",有效时间5分钟")));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        MailUtil.sendMail(mailMessage);
    }

    /**
     * 新增或修改对象
     * @param userId  用户id
     * @param type   1手机2邮箱
     * @param code  验证码
     */
    public void insertOrUpdate(Long userId,int type,String code){
        // 设置过期时间
        Date date = new Date();
        Date expireDate = DateUtils.addDateMinutes(date, 5);
        SysUserCaptcha sysUserCaptcha = get("userId", userId, "type", type);
        if (sysUserCaptcha == null){
            sysUserCaptcha = new SysUserCaptcha();
            sysUserCaptcha.setUserId(userId);
            sysUserCaptcha.setCode(code);
            sysUserCaptcha.setType(type);
            sysUserCaptcha.setExpireDate(expireDate);
            insert(sysUserCaptcha);
        }else {
            sysUserCaptcha.setExpireDate(expireDate);
            sysUserCaptcha.setCode(code);
            update(sysUserCaptcha);
        }
    }
}
